package com.doit.demo.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @DATE 2022/2/13/23:24
 * @Author MDK
 * @Version 2021.2.2
 **/
public class WordCount2 {
    public static void main(String[] args) throws Exception {
        //1.创建flink执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //2.调用Source创建DataStream
        DataStreamSource<String> lines = env.socketTextStream(args[0], Integer.parseInt(args[1]));

        //3.TransFormations
        /*SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndONe = lines.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String lines, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] words = lines.split("\\s+");
                for (String word : words) {
                    collector.collect(Tuple2.of(word, 1));
                }
            }
        });
        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = wordAndONe.keyBy(0).sum(1);*/

        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndOne = lines.flatMap(new LineSplitor());

        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = wordAndOne.keyBy(0).sum(1);

        //4.sink
        sum.print();
        //5.执行程序
        env.execute();
    }

    private static class LineSplitor implements FlatMapFunction<String, Tuple2<String, Integer>>{
        @Override
        public void flatMap(String lines, Collector<Tuple2<String, Integer>> collector) throws Exception {
            String[] words = lines.split("\\s+");
            for (String word : words) {
                collector.collect(Tuple2.of(word, 1));
            }
        }
    }
}
